package com.learn.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;

    /**
     * 配置redisTemplate
     * @return
     */
    public RedisTemplate<String,Object> redisTemplate(){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
        return  redisTemplate;
    }

    /**
     * 配置jedisCluster
     * @return
     */
    @Bean
    public JedisCluster jedisCluster(){
        Set<HostAndPort> hostAndPorts = new HashSet<>();
        hostAndPorts.add(new HostAndPort("192.168.163.128",7001));
        hostAndPorts.add(new HostAndPort("192.168.163.128",7002));
        hostAndPorts.add(new HostAndPort("192.168.163.128",7003));
        hostAndPorts.add(new HostAndPort("192.168.163.128",7004));
        hostAndPorts.add(new HostAndPort("192.168.163.128",7005));
        hostAndPorts.add(new HostAndPort("192.168.163.128",7006));
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(100);//最大空闲链接
        jedisPoolConfig.setMaxTotal(500);//最大空闲链接总数
        jedisPoolConfig.setMinIdle(0);
        jedisPoolConfig.setMaxWaitMillis(2000);//链接最大等待
        return new JedisCluster(hostAndPorts,jedisPoolConfig);
    }
}
